package city.spring.service.mealService.impl;

import city.spring.domain.entity.mealService.FoodInfoEntity;
import city.spring.domain.entity.mealService.WeekMealEntity;
import city.spring.modules.ext.entity.MealFoodExt;
import city.spring.modules.ext.service.MealFoodExtService;
import city.spring.repository.mealService.WeekMealRepository;
import city.spring.service.mealService.FoodInfoService;
import city.spring.service.mealService.FoodTypeService;
import city.spring.service.mealService.WeekMealService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Transactional(rollbackFor = Throwable.class)
@Service
public class WeekMealServiceImpl extends ServiceImpl<WeekMealRepository, WeekMealEntity> implements WeekMealService {

    private FoodInfoService foodInfoService;
    private FoodTypeService foodTypeService;
    private MealFoodExtService mealFoodExtService;

    public WeekMealServiceImpl(FoodInfoService foodInfoService, MealFoodExtService mealFoodExtService, FoodTypeService foodTypeService) {
        this.foodInfoService = foodInfoService;
        this.mealFoodExtService = mealFoodExtService;
        this.foodTypeService = foodTypeService;
    }

    @Override
    public List<WeekMealEntity> getWeekMeal(String weekId) {
        return baseMapper.getWeekMeal(weekId);
    }

    @Override
    public Map<String, List<FoodInfoEntity>> loadMealTurnFood(WeekMealEntity entity) {
        List<String> mealTurn = mealFoodExtService.getMealTurn(entity.getId());
        Map<String, List<FoodInfoEntity>> allMealTurnFood = new HashMap<>();
        for (int i = 0; i < mealTurn.size(); i++) {
            List<FoodInfoEntity> foodInfoEntities = foodInfoService.getMealTurnFood(entity.getId(), mealTurn.get(i));
            allMealTurnFood.put(mealTurn.get(i), foodInfoEntities);
        }
        return allMealTurnFood;
    }

    @Override
    public Map<String, Map<Integer, List<FoodInfoEntity>>> loadVotesMealTurnFood(WeekMealEntity entity) {
        List<Integer> votes = mealFoodExtService.getVotes(entity.getId());
        List<String> mealTurn = mealFoodExtService.getMealTurn(entity.getId());
        Map<String, Map<Integer, List<FoodInfoEntity>>> votesMealTurn = new HashMap<>();
        for (int i = 0; i < mealTurn.size(); i++) {
            List<FoodInfoEntity> foodInfoEntities = foodInfoService.getMealTurnFood(entity.getId(), mealTurn.get(i));
            Map<Integer, List<FoodInfoEntity>> votesFood = new HashMap<>();
            votesFood.put(votes.get(i), foodInfoEntities);
            votesMealTurn.put(mealTurn.get(i), votesFood);
        }
        return votesMealTurn;
    }

    @Override
    public Map<String, List<FoodInfoEntity>> currentFood(List<String> diseaseId, LocalDate date, LocalTime startTime, LocalTime endTime) {
        List<FoodInfoEntity> foodInfoEntities = new LinkedList<>();
        List<FoodInfoEntity> normalFoodInfoEntities = foodInfoService.getCurrentNormalFood(diseaseId, date, startTime, endTime);
        List<FoodInfoEntity> forbiddenFoodInfoEntities = foodInfoService.getCurrentDiseaseFood(diseaseId, date, startTime, endTime, 0);
        for (int i = 0; i < forbiddenFoodInfoEntities.size(); i++) {
            forbiddenFoodInfoEntities.get(i).setForbiddenOrRecommend("不推荐");
        }
        List<FoodInfoEntity> recommendFoodInfoEntities = foodInfoService.getCurrentDiseaseFood(diseaseId, date, startTime, endTime, 1);
        for (int i = 0; i < recommendFoodInfoEntities.size(); i++) {
            recommendFoodInfoEntities.get(i).setForbiddenOrRecommend("推荐");
        }
        foodInfoEntities.addAll(normalFoodInfoEntities);
        foodInfoEntities.addAll(forbiddenFoodInfoEntities);
        foodInfoEntities.addAll(recommendFoodInfoEntities);
        List<List<FoodInfoEntity>> currentFood = new LinkedList<>();
        foodInfoEntities.stream().collect(Collectors.groupingBy(FoodInfoEntity::getFoodId, Collectors.toList()))
                .forEach((foodId, foodListByfoodId) -> {
                    currentFood.add(foodListByfoodId);
                });
        Map<String, List<FoodInfoEntity>> newMap = new HashMap<>();
        for (int i = 0; i < currentFood.size(); i++) {
            newMap.put(foodTypeService.getById(currentFood.get(i).get(0).getFoodId()).getType(), currentFood.get(i));
        }
        return newMap;
    }

    @Override
    public Map<String, List<FoodInfoEntity>> currentFoodList(LocalDate date, LocalTime startTime, LocalTime endTime) {
        List<FoodInfoEntity> foodInfoEntities = foodInfoService.getCurrentFoodAll(date, startTime, endTime);
        List<List<FoodInfoEntity>> currentFood = new LinkedList<>();
        foodInfoEntities.stream().collect(Collectors.groupingBy(FoodInfoEntity::getFoodId, Collectors.toList()))
                .forEach((foodId, foodListByfoodId) -> {
                    currentFood.add(foodListByfoodId);
                });
        Map<String, List<FoodInfoEntity>> newMap = new HashMap<>();
        for (int i = 0; i < currentFood.size(); i++) {
            newMap.put(foodTypeService.getById(currentFood.get(i).get(0).getFoodId()).getType(), currentFood.get(i));
        }
        return newMap;
    }

    @Override
    public void setMealFood(WeekMealEntity entity, String mealTurn) {
        String mealWeekId = entity.getId();
        List<FoodInfoEntity> foodInfoEntities = entity.getFoodInfoEntities();
        for (int i = 0; i < foodInfoEntities.size(); i++) {
            MealFoodExt mealFoodExt = new MealFoodExt(null, mealWeekId, foodInfoEntities.get(i).getId(), mealTurn, 0);
            mealFoodExtService.save(mealFoodExt);
        }
    }

    @Override
    public void updateMealFood(WeekMealEntity entity, String mealTurn) {
        String mealWeekId = entity.getId();
        List<MealFoodExt> exts = mealFoodExtService.getMealFoodExt(mealWeekId, mealTurn);
        int votes = exts.get(0).getVotes();
        this.deleteMealFood(entity, mealTurn);
        List<FoodInfoEntity> foodInfoEntities = entity.getFoodInfoEntities();
        for (int i = 0; i < foodInfoEntities.size(); i++) {
            MealFoodExt mealFoodExt = new MealFoodExt(null, mealWeekId, foodInfoEntities.get(i).getId(), mealTurn, votes);
            mealFoodExtService.save(mealFoodExt);
        }
    }

//    @Override
//    public void loadRecipesVotes(WeekMealEntity entity){
//        List<RecipesVotesEntity> entities = recipesVotesService.getRecipesVotes(entity.getId());
//        entity.setRecipesVotesEntities(entities);
//    }

    @Override
    public void deleteMealFood(WeekMealEntity entity, String mealTurn) {
        String mealWeekId = entity.getId();
        List<MealFoodExt> exts = mealFoodExtService.getMealFoodExt(mealWeekId, mealTurn);
        for (int i = 0; i < exts.size(); i++) {
            mealFoodExtService.lambdaUpdate().eq(MealFoodExt::getId, exts.get(i).getId()).remove();
        }
//        List<String> extIds = mealFoodExtService.getMealFoodId(mealWeekId,mealTurn);
    }

    @Override
    public void updateMealFoodVotes(WeekMealEntity entity, String mealTurn, int votes) {
        String mealWeekId = entity.getId();
        this.deleteMealFood(entity, mealTurn);
        List<FoodInfoEntity> foodInfoEntities = entity.getFoodInfoEntities();
        for (int i = 0; i < foodInfoEntities.size(); i++) {
            MealFoodExt mealFoodExt = new MealFoodExt(null, mealWeekId, foodInfoEntities.get(i).getId(), mealTurn, votes);
            mealFoodExtService.save(mealFoodExt);
        }
    }

    @Override
    public void saveWeekMeal(WeekMealEntity entity) {
//        RecipesWeekEntity recipesWeekEntity = recipesWeekService.getById(entity.getWeekId());
//        RecipesEntity recipesEntity = recipesService.getById(recipesWeekEntity.getRecipesId());
//        Date dateStartTime = Date.from(recipesWeekEntity.getWeek().atStartOfDay(ZoneId.systemDefault()).toInstant());
//        Calendar calendar = Calendar.getInstance();
//        calendar.setFirstDayOfWeek(Calendar.MONDAY);
//        calendar.setTime(dateStartTime);
//        String year = (new SimpleDateFormat("yyyy")).format(dateStartTime);
//        int week = calendar.get(Calendar.WEEK_OF_YEAR);
//        String yearWeek = year+"年第"+week+"周";
//        String simpleMark = "周"+entity.getMealDay();
//        if(entity.getMealTime() == 1){
//            simpleMark+="早餐";
//        }else if(entity.getMealTime() == 2){
//            simpleMark+="中餐";
//        }else {
//            simpleMark+="晚餐";
//        }
//        entity.setMarker(recipesEntity.getRecipesName()+yearWeek+simpleMark);
//        entity.setSimpleMaker(simpleMark);
        boolean save = this.save(entity);
        if (!save) {
            throw new RuntimeException("保存失败！");
        }
    }

    @Override
    public void updateWeekMeal(WeekMealEntity entity) {
        lambdaUpdate()
                .set(WeekMealEntity::getMealTime, entity.getMealTime())
                .set(WeekMealEntity::getMealDay, entity.getMealDay())
                .set(WeekMealEntity::getWeekId, entity.getWeekId())
                .set(WeekMealEntity::getGmtCreate, entity.getGmtCreate())
                .set(WeekMealEntity::getGmtModified, entity.getGmtModified())
                .eq(WeekMealEntity::getId, entity.getId())
                .update();
    }

    @Override
    public void deleteWeekMeal(String primaryKey) {
        removeById(primaryKey);
        mealFoodExtService.lambdaUpdate().in(MealFoodExt::getMealWeekId, primaryKey).remove();
    }

    @Override
    public void deleteWeekMeal(List<String> primaryKeys) {
        removeByIds(primaryKeys);
        mealFoodExtService.lambdaUpdate().in(MealFoodExt::getMealWeekId, primaryKeys).remove();
    }

}
